﻿using LedControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xiaowei.Services
{
    public static class LEDStateManager
    {
        private static SortedSet<AttachStateEnum> attachState=new SortedSet<AttachStateEnum>();
        private static MainStateEnum mainState = MainStateEnum.idle;
        public static void SetState(MainStateEnum state)
        {
            if(mainState!=state)
            {
                mainState = state;
                SetLEDState();
            }
        }
        public static void SetAttachState(AttachStateEnum state)
        {
            if (!attachState.Contains(state))
            {
                attachState.Add(state);
                SetLEDState();
            }
        }
        public static void RemoveAttachState(AttachStateEnum state)
        {
            if(attachState.Contains(state))
            {
                attachState.Remove(state);
                SetLEDState();
            }   
        }
        public static LedState LedState { get; set; } = LedState.Idle;
        static async void SetLEDState()
        {
            
            if(attachState.Count==0)
            {
                switch (mainState)
                {
                    case MainStateEnum.idle:
                        LedState = LedState.Idle;
                        break;
                    case MainStateEnum.listening:
                        LedState = LedState.Listening;
                        break;
                    case MainStateEnum.thinking:
                        LedState = LedState.Thinking;
                        break;
                    case MainStateEnum.speaking:
                        LedState = LedState.Speaking;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (attachState.Max)
                {
                    case AttachStateEnum.micOff:
                        LedState = LedState.MicOff;
                        break;
                    case AttachStateEnum.error1:
                    case AttachStateEnum.error2:
                    case AttachStateEnum.error3:
                        LedState = LedState.Error;
                        break;
                    default:
                        break;
                }
            }
            LedControl.LedControl.SetLedState((LedControl.LedState)(byte)LedState);
        }
        public enum MainStateEnum
        {
            idle = 1,
            listening = 2,
            thinking = 3,
            speaking = 4,
        }
        public enum AttachStateEnum
        {
            micOff = 1,
            error1 = 2,
            error2 = 3,
            error3 = 4,
        }
    }
}
